#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 310;
int T[N][N];
int m;

// zdl:: 方向数组
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
int dist[N][N];
int main()
{
    memset(T, 0x3f, sizeof(T));
    cin >> m;
    while (m--)
    {
        int x, y, t;
        cin >> x >> y >> t;
        T[x][y] = min(T[x][y], t);
        for (int k = 0; k < 4; k++)
        {
            int x1 = x + dx[k], y1 = y + dy[k];
            if (x1 < 0 || y1 < 0)
                continue;
            T[x1][y1] = min(T[x1][y1], t);
        }
    }
    // for (int i = 0; i < 6; i++)
    // {
    //     for (int j = 0; j < 6; j++)
    //     {
    //         cout << (T[i][j] == 0x3f3f3f3f? 0 : T[i][j] )<< " ";
    //     }
    //     cout << endl;
    // }
    memset(dist, 0x3f, sizeof(dist));
    queue<pair<int, int>> q;
    q.emplace(0, 0);
    while (q.size())
    {
        auto t = q.front();
        q.pop();
        int x = t.first, y = t.second;

        for (int k = 0; k < 4; k++)
        {
            int x1 = x + dx[k], y1 = y + dy[k];
            if (x1 < 0 || y1 < 0 || dist[x1][y1] != 0x3f3f3f3f)
                continue;
            if (dist[x][y] + 1 >= T[x1][y1])
                continue;

            // cout << x1 << ":" << y1 << endl;
            dist[x1][y1] = dist[x][y] + 1;

            if (T[x1][y1] == 0x3f3f3f3f)
            {
                cout << dist[x][y] + 1 << endl;
                goto end;
            }
            q.emplace(x1, y1);
        }
    }

    cout << -1 << endl;
end:;

    return 0;
}